package org.i1510.mflow.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.i1510.common.bean.PageBean;
import org.i1510.common.utils.DateUtils;
import org.i1510.common.utils.IDGenerator;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.i1510.mflow.dao.IMflowMainDao;
import org.i1510.mflow.dao.IMflowNotifyDao;
import org.i1510.mflow.po.MflowMain;
import org.i1510.mflow.po.MflowNotify;
import org.i1510.mflow.po.MflowTpl;
import org.i1510.mflow.service.IMflowMainService;
import org.i1510.mflow.service.IMflowTplService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/admin/mflowMain")
public class MflowMainController {
    private static final Logger logger = LoggerFactory.getLogger(MflowMainController.class);
    @Autowired
    private IMflowMainService iMflowMainService;
    @Autowired
    private IMflowMainDao iMflowMainDao;
    
    private ResultMapper mapper;
    @Autowired
    private IMflowTplService iMflowTplService;
    @Autowired
    private IMflowNotifyDao iMflowNotifyDao;
    
    @RequestMapping(value = "/saveFlow", method = {RequestMethod.POST,RequestMethod.GET})
    public String saveFlow(HttpServletRequest request,@Valid @ModelAttribute("mflowMain") MflowMain mflowMain,BindingResult errors) {

    
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
        	//先保存当前节点
        	mapper = iMflowMainService.save(mflowMain,request);
        	//判断当前操作是驳回，催办，通过
        	if(mflowMain.getDocStatus().equals("20")){//审批通过
        		//获取下一节点信息 如果下一节点找不到则设置流程主节点状态 为发布(30)
        		Map conditions = new HashMap();
                MflowMain findNextNode = new MflowMain();
                findNextNode.setFdMflowMain(mflowMain.getFdMflowMain());
                findNextNode.setFdNodeId(mflowMain.getFdNodeId()+1);
                List findNextNodeList = iMflowMainService.getFlowMain(findNextNode, conditions);
                if(findNextNodeList.size() == 1){//理论上只有一条
                	Map findNextNodeMap = (Map)findNextNodeList.get(0);
                	//更新流程主节点
            		MflowMain updateMain = new MflowMain();
            		updateMain.setDocId(mflowMain.getFdMflowMain());
            		updateMain.setDocLastTime(DateUtils.getNow());
            		updateMain.setDocLastor(UserUtils.getSessionUserBean(request).getSysUser().getDocId()); 
            		updateMain.setDocStatus(findNextNodeMap.get("docStatus") + "");//节点审批状态
            		updateMain.setFdCurDesc(findNextNodeMap.get("fdDesc") + "");//当前节点审批内容
            		updateMain.setFdCurNodeId(Integer.valueOf(findNextNodeMap.get("fdDesc")+""));//当前节点            		
            		updateMain.setFdCurWxOpenId(findNextNodeMap.get("fdWxOpenId")+"");//当前节点审批人
            		mapper = iMflowMainService.save(updateMain,request);
                }else{//如果找不到下一节点 就是发布状态
                	//更新流程主节点
            		MflowMain updateMain = new MflowMain();
            		updateMain.setDocId(mflowMain.getFdMflowMain());
            		updateMain.setDocLastTime(DateUtils.getNow());
            		updateMain.setDocLastor(UserUtils.getSessionUserBean(request).getSysUser().getDocId()); 
            		updateMain.setDocStatus("30");//节点审批状态
            		updateMain.setFdCurDesc("");//当前节点审批内容
            		updateMain.setFdCurNodeId(0);//当前节点            		
            		updateMain.setFdCurWxOpenId("");//当前节点审批人
            		mapper = iMflowMainService.save(updateMain,request);
                }
        		
        	}else if(mflowMain.getDocStatus().equals("21")){//催办
        		//节点不变
        		//更新流程主节点
        		MflowMain updateMain = new MflowMain();
        		updateMain.setDocId(mflowMain.getFdMflowMain());
        		updateMain.setDocLastTime(DateUtils.getNow());
        		updateMain.setDocLastor(UserUtils.getSessionUserBean(request).getSysUser().getDocId()); 
        		updateMain.setDocStatus("21");//节点审批状态
        		updateMain.setFdCurDesc("[催办]");//当前节点审批内容     		
        		mapper = iMflowMainService.save(updateMain,request);
        		
        	}else if(mflowMain.getDocStatus().equals("22")){//驳回
        		//获取下一节点信息
        		Map conditions = new HashMap();
                MflowMain findNextNode = new MflowMain();
                findNextNode.setFdMflowMain(mflowMain.getFdMflowMain());
                findNextNode.setFdNodeId(mflowMain.getFdNodeId()-1);
                List findNextNodeList = iMflowMainService.getFlowMain(findNextNode, conditions);
                if(findNextNodeList.size() == 1){//理论上只有一条
                	Map findNextNodeMap = (Map)findNextNodeList.get(0);
                	//更新流程主节点
            		MflowMain updateMain = new MflowMain();
            		updateMain.setDocId(mflowMain.getFdMflowMain());
            		updateMain.setDocLastTime(DateUtils.getNow());
            		updateMain.setDocLastor(UserUtils.getSessionUserBean(request).getSysUser().getDocId()); 
            		updateMain.setDocStatus(findNextNodeMap.get("docStatus") + "");//节点审批状态
            		updateMain.setFdCurDesc(findNextNodeMap.get("fdDesc") + "");//当前节点审批内容
            		updateMain.setFdCurNodeId(Integer.valueOf(findNextNodeMap.get("fdDesc")+""));//当前节点            		
            		updateMain.setFdCurWxOpenId(findNextNodeMap.get("fdWxOpenId")+"");//当前节点审批人
            		mapper = iMflowMainService.save(updateMain,request);
                }
        		
        	}
       

        }
       //获取流程时间线列表
        Map cons = new HashMap();
        MflowMain mflowMainWhere = new MflowMain();
        mflowMainWhere.setFdMflowMain(mflowMain.getFdMflowMain());
        List lineTimeList = iMflowMainService.getFlowMain(mflowMainWhere, cons);
        request.setAttribute("lineTimeList",lineTimeList);
    	return "forward:/wx/mflow/wx_flow/line_time.jsp";
    }
    /**
    *@Author Rambo
    *@Desc：根据模版ID创建流程
    *@param request
    *@param mflowTpl
    *@param errors
    *@return TODO
    *@Version  MflowMainController.java,v 1.1 2015-5-14 上午3:08:09 
    */
    @RequestMapping(value = "/createFlow", method = {RequestMethod.POST,RequestMethod.GET})
    public String createFlow(HttpServletRequest request,@Valid @ModelAttribute("mflowTpl") MflowTpl mflowTpl,BindingResult errors) {

    	String mflowMainId = "";//主流程ID
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
        	//查找流程对应模版
        	  MflowTpl tpl = iMflowTplService.findById(mflowTpl.getDocId());
        	//找到节点人员
        	String[] nodes = tpl.getFdNodes().split("@");
        	for (int i = 0; i < nodes.length; i++) {
        		MflowMain saved = null;
        		MflowMain mflowMain = new MflowMain();
        		mflowMain.setDocId(IDGenerator.getGenerateID());
        		mflowMain.setDocCreateTime(DateUtils.getNow());
        		mflowMain.setDocCreator(UserUtils.getSessionUserBean(request).getSysUser().getDocId());         
        		mflowMain.setDocSubject(tpl.getDocSubject());
        		mflowMain.setFdMflowTpl(tpl.getDocId());//模版ID
        		 //创建流程 
        		if(i == 0){//0节点
        			mflowMain.setDocStatus("10");//草稿
            		mflowMain.setFdNodeId(i);//节点ID
            		mflowMain.setFdCurWxOpenId(UserUtils.getSessionUserBean(request).getSysUser().getDocId());//当前节点审批人
            		mflowMain.setFdCurNodeId(i);//当前节点ID
            		mflowMain.setFdCurDesc("[草稿]");
            		mflowMain.setFdDesc("[草稿]");
            		mflowMain.setFdMflowMain(mflowMain.getDocId());//设置主流程ID 0节点为自己本身
            		saved = iMflowMainDao.save(mflowMain); 
            		mflowMainId = saved.getDocId();
        		}else{
        			mflowMain.setDocStatus("23");//待审
            		mflowMain.setFdNodeId(i);//节点ID
            		mflowMain.setFdDesc("[待审]");
            		mflowMain.setFdWxOpenId(UserUtils.getSessionUserBean(request).getSysUser().getDocId());//节点审批人
            		mflowMain.setFdMflowMain(mflowMainId);//设置主流程ID
            		saved = iMflowMainDao.save(mflowMain); 
        		}
        		//
        		 
			}
       

        }
        //根据流程ID 当前人ID匹配流程节点进入草稿界面
        Map conditions = new HashMap();
        MflowMain find = new MflowMain();
        find.setFdMflowMain(mflowMainId);
        find.setDocCreator(UserUtils.getSessionUserBean(request).getSysUser().getDocId());
        List list = iMflowMainService.getFlowMain(find, conditions);
        if(list.size() >0){//理论上应该是 第一条是流程主节点
        	request.setAttribute("baseMap",(Map) list.get(0));
        	request.setAttribute("baseList",list);
        	return "forward:/wx/mflow/wx_flow/flow_edit.jsp?mflowMainId="+mflowMainId;
        }else{
        	return "forward:/wx/mflow/wx_flow/flow_edit.jsp?mflowMainId="+mflowMainId;
        }
    }
    @RequestMapping(value = "/jqList", method = RequestMethod.GET)
	@ResponseBody
	public String jqList(@ModelAttribute("limit") String limit,@ModelAttribute("offset") String offset,@ModelAttribute("search") String search,
					@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,
					@Valid @ModelAttribute("mflowMain") MflowMain mflowMain,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			if(!StringUtils.isStringEmpty(limit) && !StringUtils.isStringEmpty(offset) ){
				pageBean.setPageNo(String.valueOf(StringUtils.String2Integer(offset)/StringUtils.String2Integer(limit)+1));
				pageBean.setPageSize(limit);
			}
			List  wxTextMessages = iMflowMainService.getPage(mflowMain, pageBean,conditions);
			int totalCount =  iMflowMainService.getPageCount(mflowMain,conditions);
		
			mapperRtn.appendResult("total", totalCount);
			mapperRtn.appendResult("rows",wxTextMessages);		
		}		
		return mapperRtn.toJson();
	}
    /**
    *@Author Rambo
    *@Desc：保存对象
    *@param mflowMain
    *@param errors
    *@return TODO
    *@Version  MflowMainController.java,v 1.1 2013-11-15 下午4:20:56 
    */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(HttpServletRequest request,@Valid @ModelAttribute("mflowMain") MflowMain mflowMain,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            mflowMain.setDocStatus("10");
            mapper = iMflowMainService.save(mflowMain,request);
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：删除对象
    *@param docId
    *@param errors
    *@return TODO
    *@Version  MflowMainController.java,v 1.1 2014-9-2 下午3:38:17 
    */
    @RequestMapping(value = "/deleteX", method = RequestMethod.POST)
    @ResponseBody
    public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            mapper = iMflowMainService.delete(docId);
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：查看对象
    *@param docId
    *@param errors
    *@return TODO
    *@Version  MflowMainController.java,v 1.1 2014-9-2 下午3:39:35 
    */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            MflowMain mflowMain = iMflowMainService.findById(docId);
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", mflowMain);
        }        
        return mapperRtn.toJson();
    }
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String list(@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("mflowMain") MflowMain mflowMain,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            conditions.put("fromDate", fromDate);
            conditions.put("toDate", toDate);
            List  mflowMains = iMflowMainService.getPage(mflowMain, pageBean,conditions);
            int totalCount =  iMflowMainService.getPageCount(mflowMain,conditions);
            Map map = new HashMap();
            map.put("pageNo", pageBean.getPageNo());
            map.put("pageSize", pageBean.getPageSize());
            map.put("totalCount", totalCount);
            map.put("listData",mflowMains);
            
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", map);
        }        
        return mapperRtn.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：状态修改
    *@param request
    *@param docId
    *@param docStatus
    *@param errors
    *@return TODO
    *@Version  CateController.java,v 1.1 2014-9-11 上午10:06:04 
    */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            if(!StringUtils.isStringEmpty(docId)){
                MflowMain mflowMain = new MflowMain();
                
                mflowMain.setDocId(docId);
                mflowMain.setDocStatus(docStatus);
                mapper = iMflowMainService.save(mflowMain,request);
            }else{
                mapper = ResultMapper.generateFailure();
                mapper.appendResult("messages", "无法找到该ID!");
            }
            
        }
        
        return mapper.toJson();
    }
}